package utility.database;

import constant.DatabaseConstant;
import utility.file.PropertiesLoader;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author lit
 * @date 2018/3/20.
 */
public class SqlServerAccess {

    /**
     * 获取sqlserver数据库的连接
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public static Connection getInstance() throws SQLException, ClassNotFoundException {
        String host = PropertiesLoader.getParameter(DatabaseConstant.SQLSERVER_HOST_KEY,DatabaseConstant.SQLSERVER_HOST_DEFAULT);
        String port = PropertiesLoader.getParameter(DatabaseConstant.SQLSERVER_PORT_KEY,DatabaseConstant.SQLSERVER_PORT_DEFAULT);
        String database = PropertiesLoader.getParameter(DatabaseConstant.SQLSERVER_DATABASE_KEY,DatabaseConstant.SQLSERVER_DATABASE_DEFAULT);
        String url = String.format("jdbc:sqlserver://%s:%s;DatabaseName=%s",host,port,database);
        String user = PropertiesLoader.getParameter(DatabaseConstant.SQLSERVER_USER_KEY,DatabaseConstant.SQLSERVER_USER_DEFAULT);
        String password = PropertiesLoader.getParameter(DatabaseConstant.SQLSERVER_PASSWORD_KEY,DatabaseConstant.SQLSERVER_PASSWORD_DEFAULT);
        String driverName = DatabaseConstant.DRIVER_NAME_SQLSERVER;
        return DatabaseAccess.getConnection(driverName,url,user,password);
    }

    public static void closeConnection(Connection conn, Statement statement, ResultSet resultSet){
        //关闭结果集
        if(resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        //关闭声明
        if(statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        //关闭连接
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
